<template>
  <div class="registerDetail">
    <div class="task_header">
      <div class="top_title">
        <div class="top_title_back" @click="onClickLeft"><i class="iconfont icon-back"></i></div>
        <div class="top_title_val">
          {{ $route.meta.title }}
        </div>
        <div class="top_title_right" @click="goUploadRecord">上传记录</div>
      </div>
    </div>
    <div class="tabs-ctn">
      <van-tabs v-model="dataSource.insType">
        <van-tab title-class="tab-title" v-for="(item, index) in insuranceList" :title="item.name" :name="item.name" :key="index"> </van-tab>
      </van-tabs>
    </div>
    <!-- 表单 -->
    <div class="formData">
      <van-form ref="form">
        <van-field
          v-model="dataSource.fixNumberName"
          name="维修中心"
          label="维修中心"
          input-align="right"
          placeholder="请选择"
          right-icon="arrow"
          @click="handleSelect('fixNumber', 'fixNumberName', 'fixId')"
          :rules="[{ required: true }]"
          readonly
        />
        <van-field
          v-model="dataSource.brandNumberName"
          readonly
          name="品牌"
          label="品牌"
          placeholder="请选择"
          input-align="right"
          :rules="[{ required: true }]"
          right-icon="arrow"
          @click="handleSelect('brandNumber', 'brandNumberName', 'brandId')"
        />
        <van-field
          v-model="dataSource.hallNumberName"
          readonly
          name="展厅"
          label="展厅"
          input-align="right"
          placeholder="请选择"
          :rules="[{ required: true }]"
          right-icon="arrow"
          @click="handleSelect('hallNumber', 'hallNumberName', 'hallId')"
        />
        <van-field
          v-model="dataSource.insCompany"
          readonly
          name="保险公司"
          label="保险公司"
          input-align="right"
          placeholder="机器人可正常识别保司的勿选"
          right-icon="arrow"
          @click="handleSelect('repairInsCmpNumber', 'insCompany', 'repairInsCmpId')"
        />
        <!-- <van-field name="radio" label="保险类型" input-align="right">
          <template #input>
            <van-radio-group v-model="dataSource.insType" direction="horizontal">
              <van-radio :name="item.value" v-for="(item, index) in insuranceList" :key="index">
                {{ item.name }}
              </van-radio>
            </van-radio-group>
          </template>
        </van-field> -->

        <van-field name="uploader" label="商业险" input-align="right">
          <template #input>
            <van-uploader
              v-model="uploader"
              :after-read="comInsFileUpload"
              :max-count="1"
              accept=".pdf"
              @delete="(file, detail) => delComInsFile(file, detail)"
            >
              <div class="uploadbtn">上传</div>
              <!-- <van-button icon="plus" type="info" size="small"></van-button> -->
              <!-- <template>
                <div class="preview-cover van-ellipsis">{{ file.name }}</div>
              </template> -->
            </van-uploader>
          </template>
        </van-field>
        <van-field name="uploader" label="交强险" input-align="right">
          <template #input>
            <van-uploader
              v-model="uploader1"
              :after-read="trafficFileUpload"
              :max-count="1"
              accept=".pdf"
              @delete="(file, detail) => delTrafficFile(file, detail)"
            >
              <div class="uploadbtn">上传</div>

              <!-- <van-button icon="plus" type="info" size="small">上传</van-button> -->
            </van-uploader>
          </template>
        </van-field>

        <!-- 下拉选择弹窗 -->
        <van-popup v-model="showSelectPicker" position="bottom">
          <van-field
            name="模糊查询"
            input-align="left"
            v-model="likeWho"
            label="模糊查询"
            v-if="likeWhoField == 'fixNumber' || likeWhoField == 'repairInsCmpNumber'"
            placeholder="请输入模糊查询关键词"
          />
          <van-picker show-toolbar :columns="columns" @confirm="handleSelectConfirm" @cancel="showSelectPicker = false" value-key="name" />
        </van-popup>
      </van-form>
    </div>
    <div class="info_ins">
      当前选择的机器人为
      <div class="info_robot">{{ dataSource.insType }}机器人</div>
    </div>
    <div class="addBtn">
      <div class="flex">
        <div class="footerBtn comfirmBtn" @click.stop="formOnSubmit">确认</div>
        <!-- <div class="footerBtn cancelBtn" @click.stop="goUploadRecord">上传记录</div> -->
      </div>
    </div>

    <div class="loading" v-if="loading">
      <van-loading size="30px" class="loadbox" color="#fff" text-color="#fff">上传中...</van-loading>
      <div class="mask"></div>
    </div>
  </div>
</template>

<script>
import { Empty, Field, Form, Loading, Notify, Search, Toast, Uploader } from 'vant'
import { getCookies } from '../../utils/util'
import commonApi from '@/api/commonApi'
import policyApi from '@/api/policyApi'

export default {
  name: 'policyRobot',
  components: {
    Search,
    Empty,
    Field,
    Form,
    Uploader,
    Loading,
    Notify,
    Toast,
  },
  data() {
    return {
      showTimerPicker: false,
      dataSource: {
        fixNumber: '',
        fixNumberName: '',
        fixId: '',
        brandNumber: '',
        brandNumberName: '',
        files: [],
        hallNumber: '',
        hallNumberName: '',
        insType: '续保',
        repairInsCmpNumber: '',
        insCompany: '',
        repairInsCmpId: '',
      },
      uploader: [],
      uploader1: [],
      columns: [],
      showSelectPicker: false,
      disabled: false,
      field: '',
      fieldName: '',
      fieldId: '',
      showMultipleVisible: false,
      empList: [],
      userId: getCookies('userId'),
      fixCenterList: [],
      showOrgList: [],
      brandList: [],
      insureList: [], // 保险公司列表
      originalColumns: [], // 用于模糊查询时，保存原始列表
      insuranceList: [
        { name: '续保', value: '续保' },
        { name: '新车投保', value: '新车投保' },
      ],
      comInsFile: '', //商业险
      trafficFile: '', //交强险
      likeWhoField: '',
      likeWho: '',
      loading: false,
    }
  },
  watch: {
    // likeWho: function (nval, oval) {
    //   if (this.likeWhoField == 'fixNumber') {
    //     if (nval) {
    //       let newArr = this.fixCenterList.filter((item) => {
    //         return item.name.indexOf(nval) > -1
    //       })
    //       console.log(newArr)
    //       this.columns = newArr
    //     } else {
    //       this.columns = this.fixCenterList
    //     }
    //   }
    // },
    likeWho: function (nval, oval) {
      console.log('nval:', nval)
      if (nval) {
        let newArr = this.originalColumns.filter((item) => {
          return item.name.toLowerCase().indexOf(nval) > -1
        })
        // console.log(newArr)
        this.columns = newArr
      } else {
        this.columns = this.originalColumns
      }
      console.log('this.column:', this.columns)
    },
  },
  mounted() {
    this.getMainFixCenter()
    // this.getInsurance();
    this.getInsComList()
  },
  methods: {
    onClickLeft() {
      this.$router.go(-1)
    },

    // 保险公司
    getInsComList() {
      commonApi
        .getBaseCode({
          key: '保单机器人保险公司',
          userId: this.userId,
        })
        .then((res) => {
          if (res.data) {
            this.insureList = res.data
          }
        })
    },

    // 获取维修中心
    getMainFixCenter() {
      commonApi
        .getMainFixCenter({
          userId: this.userId,
          type: 'fixCenter',
        })
        .then((res) => {
          if (res.data) {
            this.fixCenterList = res.data
          }
        })
    },
    // 获取品牌
    getBrandByFixCenter() {
      commonApi
        .getBrandByFixCenter({
          fixCenterId: this.dataSource.fixId,
        })
        .then((res) => {
          if (res.data) {
            this.brandList = res.data
            this.brandList.forEach((el) => {
              if (this.dataSource.brandId == el.billId) {
                this.dataSource.brandNumber = el.number
              }
            })
          }
        })
    },
    // 获取展厅
    getShowOrgByFixCenterId() {
      commonApi
        .getShowOrgByFixCenterId({
          fixCenterId: this.dataSource.fixId,
        })
        .then((res) => {
          if (res.data) {
            this.showOrgList = res.data
            this.showOrgList.forEach((el) => {
              if (this.dataSource.hallId == el.billId) {
                this.dataSource.hallNumber = el.number
              }
            })
          }
        })
    },
    // 获取保险类型
    getInsurance() {
      commonApi
        .getEnums({
          key: 'insurance',
          userId: this.userId,
        })
        .then((res) => {
          console.log(res)
          if (res.data) {
            this.insuranceList = res.data
            this.dataSource.insurance = res.data[0].value
          }
        })
    },

    // 选择下拉
    handleSelect(field, fieldName, fieldId) {
      if (field == 'fixNumber') {
        this.columns = this.fixCenterList
      } else if (field == 'brandNumber') {
        if (!this.dataSource.fixNumber) {
          Toast('请先选择维修中心')
          return
        }
        this.columns = this.brandList
      } else if (field == 'hallNumber') {
        if (!this.dataSource.fixNumber) {
          Toast('请先选择维修中心')
          return
        }
        this.columns = this.showOrgList
      } else if (field == 'repairInsCmpNumber') {
        this.columns = this.insureList
      }
      this.originalColumns = this.columns
      this.field = field
      this.fieldName = fieldName
      this.fieldId = fieldId
      this.likeWhoField = field
      this.showSelectPicker = true
    },
    // 选择下拉确认
    handleSelectConfirm(value, index) {
      this.dataSource[this.field] = value.number
      this.dataSource[this.fieldName] = value.name
      this.dataSource[this.fieldId] = value.billId
      if (this.field == 'fixNumber') {
        this.fixNumber = ''
        this.fixNumberName = ''
        this.brandNumber = ''
        this.brandNumberName = ''
        this.getBrandByFixCenter()
        this.getShowOrgByFixCenterId()
        this.fixCenterList.forEach((item) => {
          if (item.billId == value.billId) {
            this.dataSource.brandId = item.brandId
            this.dataSource.brandNumberName = item.brandName
            this.dataSource.hallId = item.showOrgId
            this.dataSource.hallNumberName = item.showOrgName
          }
        })
        console.log(this.dataSource)
      }
      this.likeWho = ''
      this.showSelectPicker = false
    },

    comInsFileUpload(file) {
      console.log(file)
      this.comInsFile = file.file
    },
    trafficFileUpload(file) {
      this.trafficFile = file.file
    },
    delComInsFile() {
      this.comInsFile = ''
    },
    delTrafficFile() {
      this.trafficFile = ''
    },
    goUploadRecord() {
      this.$router.push('/policyRobotRecord')
    },
    formOnSubmit() {
      this.loading = true
      this.$refs.form.validate().then(() => {
        let formData = new FormData()
        if (!this.comInsFile && !this.trafficFile) {
          Notify({ type: 'danger', message: '商业险或交强险必传一项' })
          return
        }
        if (this.comInsFile) {
          const copyComInsFile = new File([this.comInsFile], '商业险.pdf')
          formData.append('files', copyComInsFile)
        }
        if (this.trafficFile) {
          const copyTrafficFile = new File([this.trafficFile], '交强险.pdf')
          formData.append('files', copyTrafficFile)
        }
        formData.append('brandNumber', this.dataSource.brandNumber)
        formData.append('hallNumber', this.dataSource.hallNumber)
        formData.append('fixNumber', this.dataSource.fixNumber)
        formData.append('insType', this.dataSource.insType)
        formData.append('insCompany', this.dataSource.insCompany)

        policyApi.uploadFlies(formData).then((res) => {
          this.loading = false
          if (res.errmsg == 'ok') {
            this.loading = false
            Notify({ type: 'success', message: '上传成功，请等待机器人录单' })
            this.uploader = []
            this.uploader1 = []
            this.delComInsFile()
            this.delTrafficFile()
          } else {
            this.loading = false
            Notify({ type: 'error', message: '上传失败' })
          }
        })
      })
      // .catch(() => {
      //   this.$toast.fail("请完善信息");
      // });
    },
  },
}
</script>

<style lang="less" scoped>
.flex {
  display: flex;
  align-items: center;
}
.registerDetail {
  background: #ebedf0;
  height: 100vh;
  overflow: hidden;
  .detail_header {
    justify-content: space-between;
    margin: 0.2rem 0.2rem;
    border-radius: 5px;
    background: #fff;
    padding: 0.3rem;
    .detail_header_lt {
      .carNo {
        font-size: 0.32rem;
        font-weight: bold;
        margin-bottom: 0.2rem;
        .icon-right {
          margin-left: 0.2rem;
          color: #409eff;
        }
      }
      .hank {
        font-size: 0.28rem;
        color: #666;
      }
    }
    .detail_header_rt {
      justify-content: flex-start;
      .txt {
        font-size: 0.28rem;
        color: #161616;
      }
      .icon-tel {
        color: #fff;
        background: #35bc04;
        font-size: 0.32rem;
        padding: 0.1rem;
        border-radius: 50%;
        margin-right: 0.1rem;
      }
    }
  }
  .tabs-ctn {
    // background: #fff;
    margin-top: 50px;
    margin-bottom: 5px;
  }
  .formData {
    // background: #fff;
    // margin-top: 50px;
  }
}

.info_ins {
  display: flex;
  justify-content: center;
  margin: 5px 0px;
  // text-align:center;
  color: gray;
  font-size: 15px;
  padding: 10px 16px;
  .info_robot {
    font-weight: bolder;
    // color:red;
  }
}
/deep/.van-field__error-message {
  text-align: right;
}

.addBtn {
  // position: fixed;
  margin-top: 0.5rem;
  bottom: 0.8rem;
  width: 100%;
  z-index: 1;
  .footerBtn {
    width: 90%;
    margin: auto;
    text-align: center;
    font-size: 0.28rem;
    padding: 0.25rem 0rem;
    border-radius: 50px;
  }
  .orderItem_filebox {
    margin: auto;
    background: #409eff;
    color: #fff;
  }
  .comfirmBtn {
    background: linear-gradient(316deg, #3975c6 0%, #71a4ea 100%);

    color: #fff;
  }
  .cancelBtn {
    color: #fff;
    background: linear-gradient(316deg, #3975c6 0%, #71a4ea 100%);
  }
}
.task_header {
  background: url('~@/assets/images/title_bg.png') no-repeat center;
  font-size: 0.24rem;
  height: 50px;
  background-size: 100% 100%;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 9;

  .top_title {
    position: relative;
    width: 100%;
    height: 50px;

    .top_title_back {
      position: absolute;
      left: 10px;
      line-height: 50px;
      color: #fff;
    }

    .top_title_val {
      text-align: center;
      line-height: 50px;
      color: #fff;
      font-weight: bold;
      font-size: 16px;
    }
    .top_title_right {
      position: absolute;
      right: 10px;
      top: 0;
      line-height: 50px;
      color: #fff;
      font-size: 16px;
    }
    .task_transbox {
      position: absolute;
      right: 10px;
      top: 5px;
      color: #fff;
      z-index: 10;
      font-weight: 400;
      font-size: 10px;
      text-align: center;
      .task_trans {
        width: 24px;
        display: block;
        margin: auto;
      }
    }
  }

  .task_header_data {
    .task_header_date {
      margin-bottom: 10px;
      display: flex;
      align-items: center;

      .task_header_date_w {
        width: 12.5%;
      }

      .task_header_date_item {
        width: 12.5%;
        text-align: center;
        color: #fff;
        font-size: 14px;
      }
    }

    .task_header_followData {
      display: flex;
      align-items: center;
      color: #fff;
      margin-bottom: 10px;

      .task_header_followData_tt {
        width: 12.5%;
        text-align: center;
      }

      .task_header_followData_item {
        width: 12.5%;
        text-align: center;
        font-size: 12px;
        font-weight: bold;
      }
    }
  }
}
.uploadbtn {
  background: linear-gradient(316deg, #3975c6 0%, #71a4ea 100%);
  font-size: 12px;
  border-radius: 5px;
  padding: 3px 20px;
  color: #fff;
}
/deep/ .van-radio__icon--checked .van-icon {
  background-color: #3975c6;
}
</style>
<style lang="less">
.tabs-ctn {
  .van-tabs__line {
    background: linear-gradient(316deg, #3975c6 0%, #71a4ea 100%);
  }
}
</style>
